import router from '@/router'
import store from '@/store'
import nprogress from 'nprogress'
import 'nprogress/nprogress.css'
import { asyncRoutes } from "@/router/index";
const whiteList = ['/login']
router.beforeEach(async (to, from, next) => {
  nprogress.start()
  if (store.state.user.token) {
    // 有token 去 login 放行
    if (to.path === '/login') {
      next('/')
      nprogress.done()
    } else {
      //用户头像信息请求
      if (!store.getters.userId){//这个判断是没有发请求时找不到用户信息就去通知vuex里面发请求  
    //获取用户头像等信息

     const res = await  store.dispatch('user/setUserInfoActions')
        console.log(res,222)
        
     
        const fileterRotuers = asyncRoutes.filter(item => res?.roles?.menus.includes(item.name))
     console.log(asyncRoutes,111)
     
     store.commit('user/setRoutesMutations', [...fileterRotuers, { path: '*', redirect: '/404', hidden: true }])
     router.addRoutes([...fileterRotuers, { path: '*', redirect: '/404', hidden: true }])
       next(to.path)
        }
      next()
    }

  } else {//如果没有token
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next('/login')
      nprogress.done()
    }

  }

})
router.afterEach(() => {
  nprogress.done()
}
)